package com.wujunshen.algorithm.leetcode.basic;

import java.util.Stack;

import lombok.extern.slf4j.Slf4j;

/**
 * @author frank woo(吴峻申) <br>
 *     email:<a href="mailto:frank_wjs@hotmail.com">frank_wjs@hotmail.com</a> <br>
 * @date 2022/7/1 22:50<br>
 */
@Slf4j
public class 字符串解码 {
  public static void main(String[] args) {
    String s = "3[a]2[bc]";
    // aaabcbc
    log.info("result is: {}", decodeString(s));

    s = "3[a2[c]]";
    // accaccacc
    log.info("result is: {}", decodeString(s));

    s = "2[abc]3[cd]ef";
    // abcabccdcdcdef
    log.info("result is: {}", decodeString(s));

    s = "abc3[cd]xyz";
    // abccdcdcdxyz
    log.info("result is: {}", decodeString(s));
  }

  private static String decodeString(String s) {
    String result = "";
    Stack<Integer> countStack = new Stack<>();
    Stack<String> resStack = new Stack<>();

    int index = 0;
    while (index < s.length()) {
      if (Character.isDigit(s.charAt(index))) {
        int count = 0;
        while (Character.isDigit(s.charAt(index))) {
          count = 10 * count + (s.charAt(index) - '0');
          index++;
        }
        countStack.push(count);
      } else if (s.charAt(index) == '[') {
        resStack.push(result);
        result = "";
        index++;
      } else if (s.charAt(index) == ']') {
        StringBuilder temp = new StringBuilder(resStack.pop());
        int repeatTimes = countStack.pop();
        for (int i = 0; i < repeatTimes; i++) {
          temp.append(result);
        }
        result = temp.toString();
        index++;
      } else {
        result += s.charAt(index++);
      }
    }
    return result;
  }
}
